﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KinSocket;
using KinSocket.Encryption;

namespace KinConquer.Sockets
{
    public unsafe class AuthSocket : KinSocket.KinSocket
    {
        public AuthSocket()
            : base(Variables.AuthPort)
        {
            
        }

        public override int OnAccept(Connection con)
        {
            con.Identifier = Program.AuthConID.NextVal;
            con.Encryption = new AuthEncryption();
            con.ActionTimer.Elapsed += delegate { Program.OnTimer(con); };
            Program.AuthConnections.Add(con.Identifier, con);
            Packets.Structures.AuthSeed seed = new Packets.Structures.AuthSeed()
            {
                Length = 8,
                Type = 1059,
                Value = 1
            };
            con.Send(&seed);
            return 0;
        }

        public override int OnReceive(Connection con, byte[] Data)
        {
            UInt16 type = BitConverter.ToUInt16(Data, 2);
            if (Packets.Delegates.PacketHandles.ContainsKey(type))
                con.ReceiveQueue.Enqueue(Data);
            else
                Console.WriteLine("Unhandled Packet: {0}", type, KinSocket.PacketConstructor.Dump(Data));
            return 0;
        }

        public override int OnDisconnect(Connection con, string Reason)
        {
            Console.WriteLine("Disconnect Invoked:\n  Socket: {0}\n  Reason: {1}", con.ConnSocket.RemoteEndPoint, Reason);
            if (Program.AuthConnections.ContainsKey(con.Identifier))
                Program.AuthConnections.Remove(con.Identifier);
            return 0;
        }

        public override int OnException(Exception ex)
        {
            Console.WriteLine(ex);
            return 0;
        }
    }
}
